﻿Namespace Catalog.Search
    ''' <summary>
    ''' The search call is used to search the entire catalog, 
    ''' optionally applying various filters/facets and returning 
    ''' any and all types of content that match the query.
    ''' </summary>
    Public Class CatalogQuery
        Inherits Query
        ''' <summary>
        ''' The search query.
        ''' </summary>
        Public Property SearchExpression As String

        ''' <summary>
        ''' Which facets to apply to the track catalog call.
        ''' </summary>
        Public Property Filters As Dictionary(Of QueryFilter, String)

        Public Sub New()
            MyBase.New()
            Me.Filters = New Dictionary(Of QueryFilter, String)
        End Sub

        Public Sub New(expression As String)
            Me.New()
            Me.SearchExpression = expression
        End Sub

        Public Overrides Function GetUrl() As System.Uri
            Dim url As String = Beatport.CATALOG_SEARCH_URL
            Dim queryStr As New List(Of String)

            queryStr.Add("query=" & Me.SearchExpression)

            If Me.PageSize > 0 Then
                queryStr.Add(String.Format("perPage={0}&page={1}", Me.PageSize, Me.Page))
            End If

            If Me.Sort.Count > 0 Then
                Dim sortFields As New List(Of String)

                For Each sortField In Me.Sort
                    sortFields.Add(String.Format("{0}{1}", sortField.Field.ToString, If(sortField.SortDir = QuerySortDirection.descending, " desc", "")))
                Next

                queryStr.Add("sortBy=" & String.Join(",", sortFields.ToArray))
            End If

            If Me.Filters.Count > 0 Then
                Dim filters As New List(Of String)

                For Each fil In Me.Filters
                    filters.Add(String.Format("facets[]={0}:{1}", fil.Key.ToString, fil.Value))
                Next

                queryStr.Add(String.Join("&", filters.ToArray))
            End If

            If queryStr.Count > 0 Then
                url = String.Format("{0}?{1}", url, String.Join("&", queryStr.ToArray))
            End If

            Return New Uri(url)
        End Function
    End Class
End Namespace